package com.beiing.tianshuai.tianshuai.mine.ui;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.CallLog;
import android.provider.ContactsContract;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.CursorLoader;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.beiing.tianshuai.tianshuai.R;
import com.beiing.tianshuai.tianshuai.app.AppConstant;
import com.beiing.tianshuai.tianshuai.base.BaseActivity;
import com.beiing.tianshuai.tianshuai.entity.UserInfoBean;
import com.beiing.tianshuai.tianshuai.mine.entity.CityDataBean;
import com.beiing.tianshuai.tianshuai.mine.entity.GetJsonDataUtil;
import com.beiing.tianshuai.tianshuai.mine.entity.OrderUserAddressEditDataBean;
import com.beiing.tianshuai.tianshuai.mine.presenter.OrderAddressEditPresenter;
import com.beiing.tianshuai.tianshuai.mine.view.OrderAddressEditViewImpl;
import com.beiing.tianshuai.tianshuai.util.LogUtils;
import com.beiing.tianshuai.tianshuai.widget.CustomDialog;
import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.google.gson.Gson;
import com.netease.nim.uikit.common.util.log.LogUtil;

import org.json.JSONArray;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class OrderAddressEditActivity extends BaseActivity implements OrderAddressEditViewImpl {

    /**
     * toolbar 返回按钮
     */
    @BindView(R.id.toolbar_navigation_back)
    ImageButton toolbarNavigationBack;

    /**
     * toolbar 删除按钮
     */
    @BindView(R.id.toolbar_filter_delete)
    TextView toolbarFilterDelete;

    /**
     * 用户名
     */
    @BindView(R.id.tv_address_username)
    EditText tvAddressUsername;

    /**
     * 选择用户头像按钮，开启通讯录
     */
    @BindView(R.id.iv_choose_user)
    ImageView ivChooseUser;
    /**
     * 包裹选择通讯录按钮的布局
     */
    @BindView(R.id.rl_iv_choose_user)
    RelativeLayout rlIvChooseUser;
    /**
     * 收货地址电话
     */
    @BindView(R.id.tv_address_photo)
    EditText tvAddressPhone;

    /**
     * 收货地址
     */
    @BindView(R.id.tv_address_address)
    TextView tvAddressAddress;

    /**
     * 具体收货地址
     */
    @BindView(R.id.tv_address_address_detailed)
    EditText tvAddressAddressDetailed;

    /**
     * 标签
     */
    @BindView(R.id.tv_address_label)
    TextView tvAddressLabel;

    /**
     * 家标签
     */
    @BindView(R.id.tv_address_label_home)
    TextView tvAddressLabelHome;

    /**
     * 公司标签
     */
    @BindView(R.id.tv_address_label_company)
    TextView tvAddressLabelCompany;

    /**
     * 学校标签
     */
    @BindView(R.id.tv_address_label_school)
    TextView tvAddressLabelSchool;

    /**
     * 添加标签 按钮 是image view 有错
     */
    @BindView(R.id.tv_address_label_add)
    ImageButton tvAddressLabelAdd;

    /**
     * 我的标签，编辑完成
     */
    @BindView(R.id.tv_address_label_my)
    TextView tvAddressLabelMy;

    /**
     * 我的标签修改按钮
     */
    @BindView(R.id.tv_address_label_my_edit_change)
    TextView tvAddressLabelMyEditChange;

    /**
     * 编辑标签编辑框
     */
    @BindView(R.id.ev_address_label_edit)
    EditText evAddressLabelEdit;

    /**
     * 编辑标签确认按钮
     */
    @BindView(R.id.tv_address_label_edit_sure)
    TextView tvAddressLabelEditSure;

    /**
     * 默认地址选择按钮
     */
    @BindView(R.id.iv_switch)
    ImageView ivSwitch;

    /**
     * 保存地址信息按钮
     */
    @BindView(R.id.tv_save_edit)
    TextView tvSaveEdit;

    /**
     * 默认按钮开关，默认为flash关
     */
    private boolean mSwitch;

    /**
     * 控制标签焦点
     */
    private int mTagChoose = 0;

    private ArrayList<CityDataBean> options1Items = new ArrayList<>();
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<>();

    private static final String TAG = "OrderAddressEdit";
    private static final int MSG_LOAD_SUCCESS = 0x0002;
    private static final int MSG_LOAD_FAILED = 0x0003;

    /**
     * 判断是否已经解析过一次城市json数据
     */
    private boolean isLoaded = false;

    /**
     * 省
     */
    private String mAddressProvince;

    /**
     * 市
     */
    private String mAddressCity;

    /**
     * 县
     */
    private String mAddressCounty;

    /**
     * address 状态判断，是修改还是添加，默认是ture 为修改
     */
    private boolean isEditAddress = true;

    /**
     * 地址id和用户id
     */
    private String mAddressId, mUserId;

    /**
     * 申请权限列表
     */
    private String[] BASIC_PERMISSIONS = {
            Manifest.permission.READ_CONTACTS
    };

    //标签 灰色框
    private Drawable drawableGray;
    //标签 红色框
    private Drawable drawableRed;
    //标签 半边红色框
    private Drawable drawableHalfRed;
    //标签 半边灰色框
    private Drawable drawableHalfGray;
    //红色
    private int mTextRed;
    //黑色
    private int mTextBlack;

    /**
     * 主持人
     */
    private OrderAddressEditPresenter presenter;

    public OrderAddressEditActivity() {
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_order_address_edit;
    }

    @Override
    protected void init() {

        //标签 灰色框
        drawableGray = ContextCompat.getDrawable(mContext, R.drawable.shape_bg_btn_radio_3_gray);
        //标签 红色框
        drawableRed = ContextCompat.getDrawable(mContext, R.drawable.shape_bg_btn_radio_3_red);
        //标签 半边红色框
        drawableHalfRed = ContextCompat.getDrawable(mContext, R.drawable.shape_bg_btn_radio_half_3_red);
        //标签 半边灰色框
        drawableHalfGray = ContextCompat.getDrawable(mContext, R.drawable.shape_bg_btn_radio_half_3_gray);
        //红色
        mTextRed = ContextCompat.getColor(mContext, R.color.red);
        //黑色
        mTextBlack = ContextCompat.getColor(mContext, R.color.black);

        initIntentExtras();
        initPresenter();
        mUserId = UserInfoBean.getUid(mContext);
        //getOrdersAddress();
        initListener();
    }

    /**
     * 初始化监听事件
     */
    private void initListener() {
        // 所在地区
        tvAddressAddress.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //关闭键盘
                InputMethodManager inputMethodManager = (InputMethodManager)
                        getSystemService(Context.INPUT_METHOD_SERVICE);
                inputMethodManager.hideSoftInputFromWindow(v.getWindowToken(), 0);
                if (isLoaded) {
                    showPickerView();
                } else {
                    LogUtils.i("================= 开始解析数据 ================", "initAddress");
                    Thread thread = new Thread(new Runnable() {
                        @Override
                        public void run() {
                            // 子线程中解析省市区数据
                            initJsonData();
                        }
                    });
                    thread.start();
                }
            }
        });

        // 选择联系人
        rlIvChooseUser.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //权限请求许可
                ActivityCompat.requestPermissions(OrderAddressEditActivity.this, BASIC_PERMISSIONS, AppConstant.BASIC_PERMISSION_REQUEST_CODE);
            }
        });

        // 保存按钮
        tvSaveEdit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //点击确认按钮保存数据，判断是否输入完全
                if (TextUtils.isEmpty(tvAddressUsername.getText())) {
                    showShortText("请输入姓名");
                    return;
                } else if (TextUtils.isEmpty(tvAddressPhone.getText())) {
                    showShortText("请输入联系方式");
                    return;
                } else if (TextUtils.isEmpty(tvAddressAddress.getText()) || "请选择收货地址".equals(tvAddressAddress.getText())) {
                    showShortText("请选择收货地址");
                    return;
                } else if (TextUtils.isEmpty(tvAddressAddressDetailed.getText())) {
                    showShortText("请输入具体地址");
                    return;
                }
                //收货人姓名
                String name = tvAddressUsername.getText().toString();
                //收货人联系电话
                String telephone = tvAddressPhone.getText().toString();
                //省
                String province = mAddressProvince;
                //市
                String city = mAddressCity;
                //区
                String country = mAddressCounty;
                //具体地址
                String address = tvAddressAddressDetailed.getText().toString();
                //是否是默认地址

                //我的标签,判断选择的标签
                String label = null;
                switch (mTagChoose) {
                    case 0:
                        label = tvAddressLabelHome.getText().toString();
                        break;
                    case 1:
                        label = tvAddressLabelCompany.getText().toString();
                        break;
                    case 2:
                        label = tvAddressLabelSchool.getText().toString();
                        break;
                    case 3:
                        label = tvAddressLabelMy.getText().toString();
                        break;
                    default:
                        break;
                }
                //showShortText("mSwitch"+mSwitch);
                //写入数据地址状态判断，
                if (isEditAddress) {
                    Log.i(isEditAddress + mAddressId + province + "修改", "===============");

                    presenter.getUserAddressChange(
                            mUserId, mAddressId, name, telephone,
                            province, city, country, address, label, mSwitch ? "1" : "'0'");
                } else {
                    LogUtils.i(isEditAddress + "添加" + name + telephone + province + city + country + address + label, "===============");
                    presenter.getUserAddressAdd(
                            mUserId, name, telephone, province,
                            city, country, address, label, mSwitch ? "1" : "'0'");
                }
                //返回结果码
                Intent intent = getIntent();
                setResult(AppConstant.RESULT_CODE_EDIT_RECEIVE_ADDRESS, intent);
                setResult(AppConstant.RESULT_CODE_MANAGE_RECEIVE_ADDRESS, intent);

                showShortText("保存成功");
                finish();
            }
        });
        //设置默认地址
        ivSwitch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!mSwitch) {
                    ivSwitch.setImageDrawable(ContextCompat.getDrawable(mContext, R.drawable.ic_switch_on));
                    mSwitch = true;
                } else {
                    ivSwitch.setImageDrawable(ContextCompat.getDrawable(mContext, R.drawable.ic_switch_off));
                    mSwitch = false;
                }
            }
        });
        //返回按钮，询问是否保存
        toolbarNavigationBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CustomDialog dialog = new CustomDialog(mContext, R.style.dialog, "是否放弃保存当前编辑的地址？", new CustomDialog.OnCloseListener() {
                    @Override
                    public void onClick(Dialog dialog, boolean confirm) {
                        if (confirm) {
                            dialog.dismiss();
                            finish();
                        } else {
                            dialog.dismiss();
                        }
                    }
                });
                dialog.setNegativeButton("取消");
                dialog.setPositiveButton("确认");
                dialog.setTitle("提示");
                dialog.setCanceledOnTouchOutside(true);
                dialog.show();
            }
        });
        //清空数据
        toolbarFilterDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //hortText("清空用户输入信息！");
                //显示添加按钮，自定义标签隐藏
                tvAddressLabelAdd.setVisibility(View.VISIBLE);
                tvAddressLabelMyEditChange.setVisibility(View.GONE);
                tvAddressLabelMy.setVisibility(View.GONE);
                tvAddressLabelHome.setTextColor(mTextRed);
                tvAddressLabelHome.setBackground(drawableRed);
                tvAddressLabelSchool.setTextColor(mTextBlack);
                tvAddressLabelSchool.setBackground(drawableGray);
                tvAddressLabelCompany.setTextColor(mTextBlack);
                tvAddressLabelCompany.setBackground(drawableGray);
                //姓名，手机，地区，详细地址全部清空
                tvAddressUsername.setText(null);
                tvAddressPhone.setText(null);
                tvAddressAddress.setText("请选择收货地址");
                tvAddressAddressDetailed.setText("");
            }
        });
        //添加自定义标签
        tvAddressLabelAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tvAddressLabelAdd.setVisibility(View.GONE);
                tvAddressLabelEditSure.setVisibility(View.VISIBLE);
                evAddressLabelEdit.setVisibility(View.VISIBLE);
            }
        });
        tvAddressLabelMyEditChange.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //编辑我的标签按钮
                //如果没有输入就显示添加按钮，其他的都隐藏
                if (TextUtils.isEmpty(tvAddressLabelMy.getText())) {
                    tvAddressLabelAdd.setVisibility(View.VISIBLE);
                    tvAddressLabelMyEditChange.setVisibility(View.GONE);
                    tvAddressLabelMy.setVisibility(View.GONE);
                } else {
                    //点击编辑按钮，将我的标签文字传输到添加标签编辑栏，显示添加标签编辑栏和确认按钮，隐藏我的标签和编辑按钮
                    evAddressLabelEdit.setText(tvAddressLabelMy.getText());
                    tvAddressLabelEditSure.setVisibility(View.VISIBLE);
                    evAddressLabelEdit.setVisibility(View.VISIBLE);
                    tvAddressLabelMyEditChange.setVisibility(View.GONE);
                    tvAddressLabelMy.setVisibility(View.GONE);
                }
            }
        });
        //自定义标签确认按钮
        tvAddressLabelEditSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //如果没有输入就显示添加按钮，其他的都隐藏
                if (TextUtils.isEmpty(evAddressLabelEdit.getText())) {
                    tvAddressLabelAdd.setVisibility(View.VISIBLE);
                    tvAddressLabelMyEditChange.setVisibility(View.GONE);
                    tvAddressLabelMy.setVisibility(View.GONE);
                    tvAddressLabelEditSure.setVisibility(View.GONE);
                    evAddressLabelEdit.setVisibility(View.GONE);
                } else {
                    //点击隐藏添加标签编辑栏和确认按钮，显示我的标签和编辑按钮，将编辑标签信息传输到我的标签框
                    //showShortText("确定添加标签按钮" + evAddressLabelEdit.getText());
                    tvAddressLabelMy.setText(evAddressLabelEdit.getText());
                    tvAddressLabelEditSure.setVisibility(View.GONE);
                    evAddressLabelEdit.setVisibility(View.GONE);
                    tvAddressLabelMyEditChange.setVisibility(View.VISIBLE);
                    tvAddressLabelMy.setVisibility(View.VISIBLE);
                }
            }
        });
        //点击标签，此标签为红色，其他标签全为灰色
        tvAddressLabelHome.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //设置标签状态为0
                mTagChoose = 0;
                //默认标签颜色变灰色
                tvAddressLabelHome.setBackground(drawableRed);
                tvAddressLabelSchool.setBackground(drawableGray);
                tvAddressLabelCompany.setBackground(drawableGray);
                tvAddressLabelMy.setBackground(drawableHalfGray);
                //修改文字颜色
                tvAddressLabelHome.setTextColor(mTextRed);
                tvAddressLabelSchool.setTextColor(mTextBlack);
                tvAddressLabelCompany.setTextColor(mTextBlack);
                tvAddressLabelMy.setTextColor(mTextBlack);
            }
        });
        //公司标签
        tvAddressLabelCompany.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mTagChoose = 1;
                tvAddressLabelHome.setBackground(drawableGray);
                tvAddressLabelSchool.setBackground(drawableGray);
                tvAddressLabelCompany.setBackground(drawableRed);
                tvAddressLabelMy.setBackground(drawableHalfGray);
                //修改文字颜色
                tvAddressLabelHome.setTextColor(mTextBlack);
                tvAddressLabelSchool.setTextColor(mTextBlack);
                tvAddressLabelCompany.setTextColor(mTextRed);
                tvAddressLabelMy.setTextColor(mTextBlack);
            }
        });
        tvAddressLabelSchool.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mTagChoose = 2;
                tvAddressLabelHome.setBackground(drawableGray);
                tvAddressLabelSchool.setBackground(drawableRed);
                tvAddressLabelCompany.setBackground(drawableGray);
                tvAddressLabelMy.setBackground(drawableHalfGray);
                //修改文字颜色
                tvAddressLabelHome.setTextColor(mTextBlack);
                tvAddressLabelSchool.setTextColor(mTextRed);
                tvAddressLabelCompany.setTextColor(mTextBlack);
                tvAddressLabelMy.setTextColor(mTextBlack);
            }
        });
        tvAddressLabelMy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mTagChoose = 3;
                tvAddressLabelHome.setBackground(drawableGray);
                tvAddressLabelSchool.setBackground(drawableGray);
                tvAddressLabelCompany.setBackground(drawableGray);
                tvAddressLabelMy.setBackground(drawableHalfRed);
                //修改文字颜色
                tvAddressLabelHome.setTextColor(mTextBlack);
                tvAddressLabelSchool.setTextColor(mTextBlack);
                tvAddressLabelCompany.setTextColor(mTextBlack);
                tvAddressLabelMy.setTextColor(mTextRed);
            }
        });
    }

    /**
     * 监听返回键，返回结果码
     */
    @Override
    public void onBackPressed() {
        //判断默认地址是否被修改
        CustomDialog dialog = new CustomDialog(mContext, R.style.dialog, "是否放弃保存当前编辑的地址？", new CustomDialog.OnCloseListener() {
            @Override
            public void onClick(Dialog dialog, boolean confirm) {
                if (confirm) {
                    dialog.dismiss();
                    finish();
                } else {
                    dialog.dismiss();
                }
            }
        });
        dialog.setNegativeButton("取消");
        dialog.setPositiveButton("确认");
        dialog.setTitle("提示");
        dialog.setCanceledOnTouchOutside(true);
        dialog.show();
        //super.onBackPressed();
    }

    /**
     * 获取传递的数据
     */
    private void initIntentExtras() {
        Intent intent = getIntent();
        //获取进入状态,默认为true
        isEditAddress = intent.getBooleanExtra("isEditAddress", true);

        mAddressId = intent.getStringExtra("mAddressId");
        tvAddressUsername.setText(intent.getStringExtra("name"));
        tvAddressPhone.setText(intent.getStringExtra("phone"));
        if (!TextUtils.isEmpty(intent.getStringExtra("address_address"))) {
            tvAddressAddress.setText(intent.getStringExtra("address_address"));
        }
        tvAddressPhone.setText(intent.getStringExtra("phone"));
        mAddressProvince = intent.getStringExtra("address_province");
        mAddressCity = intent.getStringExtra("address_city");
        mAddressCounty = intent.getStringExtra("address_country");
        tvAddressAddressDetailed.setText(intent.getStringExtra("address"));
        //首次进入考虑标签状态切换
        if (!TextUtils.isEmpty(intent.getStringExtra("label"))) {
            if ("家".equals(intent.getStringExtra("label"))) {
                mTagChoose = 0;
            } else if ("公司".equals(intent.getStringExtra("label"))) {
                mTagChoose = 1;
                tvAddressLabelHome.setBackground(drawableGray);
                tvAddressLabelCompany.setBackground(drawableRed);
                //tvAddressLabelMy.setBackground(drawableHalfGray);
                //修改文字颜色
                tvAddressLabelHome.setTextColor(mTextBlack);
                tvAddressLabelCompany.setTextColor(mTextRed);
                //tvAddressLabelMy.setTextColor(mTextBlack);
            } else {
                mTagChoose = 2;
                tvAddressLabelHome.setBackground(drawableGray);
                tvAddressLabelSchool.setBackground(drawableRed);
                //tvAddressLabelMy.setBackground(drawableHalfGray);
                //修改文字颜色
                tvAddressLabelHome.setTextColor(mTextBlack);
                tvAddressLabelSchool.setTextColor(mTextRed);
                //tvAddressLabelMy.setTextColor(mTextBlack);
            }
        } else {
            //如果为空，默认设置为选中第一个标签
            mTagChoose = 0;
        }
        //tvAddressLabel.setText(intent.getStringExtra("label"));
        //如果获取的def不等于空，就设置默认地址，如果为空就设置默认UI设计
        if (!TextUtils.isEmpty(intent.getStringExtra("def"))) {
            if ("1".equals(intent.getStringExtra("def"))) {
                LogUtil.i(TAG,"def"+intent.getStringExtra("def"));
                ivSwitch.setImageResource(R.drawable.ic_switch_on);
                mSwitch=true;
            } else {
                LogUtil.i(TAG,"def"+intent.getStringExtra("def"));
                ivSwitch.setImageResource(R.drawable.ic_switch_off);
                mSwitch=false;
            }
        }

    }

    /**
     * 启动activity需要的数据
     *
     * @param context          上下文
     * @param mAddressId       地址id
     * @param name             姓名
     * @param phone            联系方式
     * @param address_address  具体地址
     * @param address_province 省
     * @param address_city     市
     * @param address_country  区
     * @param address          省+市+区
     * @param label            标签
     * @param def              是否默认地址
     */
    public static void start(Context context, String mAddressId, String name, String phone,
                             String address_address, String address_province, String address_city, String address_country, String address, String label, String def) {
        Intent intent = new Intent(context, OrderAddressEditActivity.class);
        intent.putExtra("mAddressId", mAddressId);
        intent.putExtra("name", name);
        intent.putExtra("phone", phone);
        intent.putExtra("address_address", address_address);
        intent.putExtra("address_province", address_province);
        intent.putExtra("address_city", address_city);
        intent.putExtra("address_country", address_country);
        intent.putExtra("address", address);
        intent.putExtra("label", label);
        intent.putExtra("def", def);
        //context.startActivity(intent);
        ((Activity) context).startActivityForResult(intent, AppConstant.REQUEST_CODE_EDIT_RECEIVE_ADDRESS);
    }

    /**
     * 新建地址 多态
     *
     * @param context
     */
    public static void start(Context context, Boolean isEditAddress) {
        Intent intent = new Intent(context, OrderAddressEditActivity.class);
        intent.putExtra("isEditAddress", isEditAddress);
        //context.startActivity(intent);
        //强转返回参数
        ((Activity) context).startActivityForResult(intent, AppConstant.REQUEST_CODE_EDIT_RECEIVE_ADDRESS);
    }

    /**
     * 初始化 presenter
     */
    public void initPresenter() {
        presenter = new OrderAddressEditPresenter(this);

    }

    /**
     * 判断结果码，接收结果码
     *
     * @param requestCode 请求码
     * @param resultCode  结果码
     * @param data        数据
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 1: {
                if (resultCode == Activity.RESULT_OK) {
                    Uri contactData = data.getData();
                    if (contactData != null) {
                        CursorLoader cursorLoader = new CursorLoader(this, contactData, null, null, null, null);
                        Cursor cursor = cursorLoader.loadInBackground();
                        if (cursor != null) {
                            cursor.moveToFirst();
                            String phoneNumber = null;
                            String username = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                            tvAddressUsername.setText(username);
                            String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
                            ContentResolver contentResolver = getContentResolver();
                            Cursor phone = contentResolver.query(
                                    ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                                    null,
                                    ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactId,
                                    null,
                                    null
                            );
                            if (phone != null) {
                                if (phone.moveToFirst()) {
                                    int index = phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
                                    phoneNumber = phone.getString(index);
                                    tvAddressPhone.setText(phoneNumber);
                                    if (!phone.isClosed()) {
                                        phone.close();
                                    }
                                }
                            }
                            if (!cursor.isClosed()) {
                                cursor.close();
                            }
                            //获取联系人信息，需要添加两条权限来兼容版本
                            LogUtils.d(MessageFormat.format("获取到联系人信息 {0} / {1}", phoneNumber, username), TAG);
                        }
                    }
                }
                break;

            }
            default:break;
        }
    }

    @Override
    public void showProgress() {

    }

    @Override
    public void hideProgress() {

    }

    @Override
    public void onRequestSuccess(OrderUserAddressEditDataBean bean) {

    }

    @Override
    public void onRequestFailed(Throwable throwable) {

    }

    /**
     * View 层接口 方法
     *
     * @param bean 地址信息
     */
    @Override
    public void getOrderAddressEditSuccess(OrderUserAddressEditDataBean bean) {
        int code = bean.getCode();
        switch (code) {
            case 200:
                //showShortText("添加数据成功");
                break;
            case 202:
                showShortText("执行失败");
                break;
            case 401:
                showShortText("参数有误\n请将地址信息输入完整");
                break;
            default:break;
        }
    }

    @Override
    public void getOrderAddressEditError(OrderUserAddressEditDataBean bean) {

    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_LOAD_SUCCESS:
                    //showShortText("解析数据成功");
                    isLoaded = true;
                    showPickerView();
                    break;
                case MSG_LOAD_FAILED:
                    showShortText("解析数据失败");
                    isLoaded = false;
                    break;
                default:break;
            }
        }
    };

    /**
     * 显示城市选择器
     */
    private void showPickerView() {
        OptionsPickerView pvOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                mAddressProvince = options1Items.get(options1).getPickerViewText();
                mAddressCity = options2Items.get(options1).get(options2);
                mAddressCounty = options3Items.get(options1).get(options2).get(options3);
                tvAddressAddress.setText(MessageFormat.format("{0} {1} {2}",
                        mAddressProvince, mAddressCity, mAddressCounty));
            }
        }).setTitleText("所在地区")
                .setDividerColor(Color.BLACK)
                //设置选中项文字颜色
                .setTextColorCenter(Color.BLACK)
                .setContentTextSize(20)
                .build();
        //三级选择器,索引越界异常
        pvOptions.setPicker(options1Items, options2Items, options3Items);
        pvOptions.show();
    }

    /**
     * 转换json数据为实体类
     */
    private void initJsonData() {
        /*
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         */

        //获取assets目录下的json文件数据
        String jsondata = new GetJsonDataUtil().getJson(this,
                "province.json");
        //用Gson转成实体
        ArrayList<CityDataBean> cityDataBeans = parseData(jsondata);

        /*
         * 添加省份数据
         *
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        options1Items = cityDataBeans;
        //遍历省份
        for (int i = 0; i < cityDataBeans.size(); i++) {
            //该省的城市列表（第二级）
            ArrayList<String> cityList = new ArrayList<>();
            //该省的所有地区列表（第三极）
            ArrayList<ArrayList<String>> countyList = new ArrayList<>();
            //遍历该省份的所有城市
            for (int j = 0; j < cityDataBeans.get(i).getCityList().size(); j++) {
                CityDataBean.CityBean cityBean = cityDataBeans.get(i).getCityList().get(j);
                String cityName = cityBean.getName();
                //添加城市
                cityList.add(cityName);
                //该城市的所有地区列表
                ArrayList<String> countyNameList = new ArrayList<>();
                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                List<String> area = cityBean.getArea();
                if (area.isEmpty()) {
                    countyNameList.add("");
                } else {
                    countyNameList.addAll(area);
                }
                //添加该省所有地区数据
                countyList.add(countyNameList);
            }
            //添加城市数据
            options2Items.add(cityList);
            //添加地区数据
            options3Items.add(countyList);
        }
        mHandler.sendEmptyMessage(MSG_LOAD_SUCCESS);
    }

    /**
     * j
     *
     * @param json json数据
     * @return 结果
     */
    public ArrayList<CityDataBean> parseData(String json) {
        ArrayList<CityDataBean> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(json);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                CityDataBean entity = gson.fromJson(data.optJSONObject(i).toString(), CityDataBean.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
            mHandler.sendEmptyMessage(MSG_LOAD_FAILED);
        }
        return detail;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
        }
    }

    /**
     * 重写动态申请权限结果回调方法
     *
     * @param requestCode  请求码
     * @param permissions  请求权限集合
     * @param grantResults 请求结果集合
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case AppConstant.BASIC_PERMISSION_REQUEST_CODE:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    //跳转到通信录界面
                    Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
                    startActivityForResult(intent, 1);
                } else {
                    showShortText("请打开联系人读取权限");
                }
                break;
                default:break;
        }
    }
}
